from flask import Flask
from flask_socketio import SocketIO,emit
import random,json

# 创建应用实例
app=Flask(__name__)
# 生成通信密钥
app.config['SECRET_KEY']=str(random.random())
# 配置WebSocket服务
socketio=SocketIO(app,logger=True,engineio_logger=True,cors_allowed_origins='*')

# 将服务端消息转发给控制端
@socketio.on('message')
def handle_message(data):
    emit('message',data,broadcast=True)

if __name__ == '__main__':
    # 配置监听端口
    with open('static/config.json','r') as f:
        port=json.load(f)['port']['websocket']
    # 打印提示信息
    print('WebSocket Server running...')
    # 运行服务器
    socketio.run(app,host='0.0.0.0',port=port)
